﻿package com.sgcc.nfc.lock.presentation.users

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.UserProfile
import com.sgcc.nfc.lock.domain.usecase.DeleteUserUseCase
import com.sgcc.nfc.lock.domain.usecase.GetUsersUseCase
import com.sgcc.nfc.lock.domain.usecase.ResetPasswordUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch

@HiltViewModel
class UsersViewModel @Inject constructor(
    private val getUsersUseCase: GetUsersUseCase,
    private val deleteUserUseCase: DeleteUserUseCase,
    private val resetPasswordUseCase: ResetPasswordUseCase
) : ViewModel() {

    private val _users = MutableLiveData<List<UserProfile>>(emptyList())
    val users: LiveData<List<UserProfile>> = _users

    private val _message = MutableLiveData<String?>()
    val message: LiveData<String?> = _message

    init {
        loadUsers()
    }

    fun loadUsers() {
        viewModelScope.launch {
            when (val result = getUsersUseCase(page = 1, pageSize = 50)) {
                is NetworkResult.Success -> _users.value = result.data.data
                is NetworkResult.Error -> _message.value = result.message
                NetworkResult.Loading -> {}
            }
        }
    }

    fun deleteUser(userId: Long) {
        viewModelScope.launch {
            when (deleteUserUseCase(userId)) {
                is NetworkResult.Success -> {
                    _message.value = "User deleted successfully"
                    loadUsers()
                }
                is NetworkResult.Error -> _message.value = "Failed to delete user"
                NetworkResult.Loading -> {}
            }
        }
    }

    fun resetPassword(userId: Long) {
        viewModelScope.launch {
            when (resetPasswordUseCase(userId)) {
                is NetworkResult.Success -> _message.value = "Password reset successfully"
                is NetworkResult.Error -> _message.value = "Failed to reset password"
                NetworkResult.Loading -> {}
            }
        }
    }

    fun clearMessage() {
        _message.value = null
    }
}
